const {wsapilogSchema,mysql,sequelize} = require('./mysqlSequelize');
module.exports = (server, { storage, config }) => {
    var mysqlDB={}
    mysqlDB.host=storage.getProperty('host')
    mysqlDB.port=storage.getProperty('port')
    mysqlDB.username=storage.getProperty('username')
    mysqlDB.password=storage.getProperty('password')
    mysqlDB.database=storage.getProperty('database')
    mysql_connect(mysqlDB)
    
    server.on('request', (req, res) => {
      let body;
      req.on('data', (data) => {
        body = body ? Buffer.concat([body, data]) : data;
      });
      req.on('end', () => {
        var status= sequelize.connectionManager.state
        console.log('连接管理器状态:', sequelize.connectionManager.state);
//        if(authenticated.equals("authenticated")){
//        var apilog=new WSApiLog(req.originalReq)
//        apilog.req=req.originalReq
//        fullurl=req.originalReq.fullUrl
//        apilog.client_ip=req.originalReq.remoteAddress
//          const url = new URL(fullurl);
//        apilog.protocol=url.protocol
//        apilog.host=url.host
//        apilog.path=url.pathname
//        apilog.req_params=url.searchParams.toString()
         fullurl=req.originalReq.fullUrl
         const url = new URL(fullurl);
        params=fullurl.split('?')
        if (body) {
          if (req.originalReq.headers['content-type'].includes("json")){
            req_body=JSON.parse(body.toString('utf-8'))
          }
          if (params.length>1){
          url=params[0]
          }
          wsapilogSchema.create({
          id: req.originalReq.id,
          fullUrl: req.originalReq.fullUrl,
          method: req.originalReq.method,
          url: url,
          host: url.host,
          protocol: url.protocol,
          path: url.pathname,
          headers: req.originalReq.headers,
          req: req.originalReq,
          req_body: req.originalReq.body,
          req_params: url.searchParams.toString(),
          client_ip: req.originalReq.remoteAddress,
          }).then((request) => {
          console.log('请求和响应报文已保存:', request.toJSON());
           }).catch((error) => {
           console.error('保存请求和响应报文时发生错误:', error);
       });
//          apilog.save()
          req.end(body);
        } else {
//          apilog.save()
          req.end();
        }
      }}
      );
     
      req.pipe(res);
    });

//    sequelize.sync() // 创建表格（如果不存在）
//      .then(() => wsapilogSchema.create(
//      { name: 'John Doe', age: 25 }
//      )) // 创建新记录
//      .then(user => {
//        console.log('保存的用户信息:', user.toJSON());
//      })
//      .catch(error => {
//        console.error('保存数据时出错:', error);
//      });
};
